﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using McTools.Xrm.Connection;
using McTools.Xrm.Connection.WinForms;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using System.Threading;

namespace CRM_Solution_Merger
{
    public partial class CRMSolutionMerger : Form
    {
        // This thread is used to demonstrate both thread-safe and 
        // unsafe ways to call a Windows Forms control. 
        private Thread demoThread = null;
        

        /// <summary>
        /// Connection control
        /// </summary>
        CrmConnectionStatusBar ccsb;

        /// <summary>
        /// Connection manager
        /// </summary>
        ConnectionManager cManager;

        IOrganizationService service;

        public List<CRMSolution> CRMSolutionList { get; set; }

        public List<KeyValuePair<Guid, string>> PublisherList { get; set; }

        //private KeyValuePair<Guid, string> selectedSolution;

        private CRMSolution selectedSolution;

        public CRMSolutionMerger()
        {
            InitializeComponent();
            btnRetrieveSolutions.Enabled = true;
            this.cManager = new ConnectionManager();
            this.cManager.ConnectionSucceed += new ConnectionManager.ConnectionSucceedEventHandler(cManager_ConnectionSucceed);
            this.cManager.ConnectionFailed += new ConnectionManager.ConnectionFailedEventHandler(cManager_ConnectionFailed);
            this.cManager.StepChanged += new ConnectionManager.StepChangedEventHandler(cManager_StepChanged);

            // Instantiate and add the connection control to the form
            ccsb = new CrmConnectionStatusBar(this.cManager, new FormHelper(this, this.cManager));
            this.Controls.Add(ccsb);

        }

        private void cManager_StepChanged(object sender, StepChangedEventArgs e)
        {
            this.ccsb.SetMessage(e.CurrentStep);
            ////btnRetrieveSolutions.Enabled = true;
            //this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe));
            //this.demoThread.Start();
        }

        // This method is executed on the worker thread and makes 
        // an unsafe call on the TextBox control. 
        private void ThreadProcUnsafe()
        {
            //btnRetrieveSolutions.Enabled = true;
        }


        private void cManager_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            // Set error message
            this.ccsb.SetMessage("Error: " + e.FailureReason);

            // Clear the current organization service
            this.service = null;
        }

        private void cManager_ConnectionSucceed(object sender, ConnectionSucceedEventArgs e)
        {
            // Store connection Organization Service
            this.service = e.OrganizationService;

            // Displays connection status
            this.ccsb.SetConnectionStatus(true, e.ConnectionDetail);
            //btnRetrieveSolutions.Enabled = true;
            this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe));
            this.demoThread.Start();
        }

        private void btnRetrieveSolutions_Click(object sender, EventArgs e)
        {
            if (this.service == null)
            {
                MessageBox.Show("Do you want to Connect to Orgnaization first?");
                return;
            }
            CRMUtil crmUtil = new CRMUtil(this.service);

            PublisherList = crmUtil.RetrievePublisher();

            CRMSolutionList = crmUtil.RetrieveSolution(IsManaged:false);
            CreatingGrid(CRMSolutionList);
            btnMergeSolution.Enabled = true;
        }

        public void CreatingGrid(List<CRMSolution> solutionList)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.DataSource = solutionList;
            dataGridView1.Refresh();
        }

        private void btnMergeSolution_Click(object sender, EventArgs e)
        {
            MergeSolutionPopUp mergeSolPopUp = new MergeSolutionPopUp();

            DialogResult dr = mergeSolPopUp.ShowDialog(this);

            if (dr == DialogResult.Cancel)
            {
                mergeSolPopUp.Close();
            }
            else if (dr == DialogResult.OK)
            {
                selectedSolution = mergeSolPopUp.GetSolutionName();

                if (selectedSolution.SolutionId == Guid.Empty)
                {
                    chkCreateNewSol.Checked = true;
                }
                else
                {
                    chkCreateNewSol.Checked = false;
                }
                txtSolutionName.Text = selectedSolution.UniqueName;

                KeyValuePair<Guid, string> Publisher = mergeSolPopUp.GetSelectedPublisher();
                txtPublisher.Text = Publisher.Value;

                selectedSolution.PublisherId = Publisher.Key;
                
                mergeSolPopUp.Close();


                List<Guid> tobeMergedSolutionIds = new List<Guid>();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;
                    DataGridViewTextBoxCell txt = row.Cells[1] as DataGridViewTextBoxCell;

                    if (Convert.ToBoolean(chk.Value) == true)
                    {
                        //MessageBox.Show("this cell checked :" + txt.Value.ToString());
                        tobeMergedSolutionIds.Add(new Guid(txt.Value.ToString()));
                    }
                }
                if (tobeMergedSolutionIds.Count > 0)
                {
                    CRMUtil crmUtil = new CRMUtil(this.service);
                    crmUtil.MergeSolutions(selectedSolution, tobeMergedSolutionIds);
                    CRMSolutionList = crmUtil.RetrieveSolution(IsManaged: false);
                    CreatingGrid(CRMSolutionList);
                    btnMergeSolution.Enabled = true;

                    MessageBox.Show("Selected Solutions merged successfully.");
                }
                else
                {
                    MessageBox.Show("No Solution selected in Solution View.");
                }
            }
        }
    }
}
